/**
 * 邮件发送页面
 */
import React, { useState, useEffect, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Space,
  message,
  Row,
  Col,
  Switch,
  Tabs,
  Tag,
  Divider,
  Alert,
  Statistic,
  AutoComplete,
  Modal,
} from 'antd';
import {
  SendOutlined,
  EyeOutlined,
  DatabaseOutlined,
  TableOutlined,
  UserOutlined,
  MailOutlined,
  FileTextOutlined,
  PlusOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import { history } from '@umijs/max';
import IntegratedRecipientSelector from '@/components/IntegratedRecipientSelector';
import SmartRecipientInput from '@/components/SmartRecipientInput';
import TableDataInsertion from '@/components/TableDataInsertion';
import EmailEditor, { insertVariableAtCursor } from '@/components/EmailEditor';
import SystemVariablePanel from '@/components/SystemVariablePanel';
import AttachmentManager from '@/components/AttachmentManager';
import {
  sendEmail,
  previewEmailContent,
  type EmailSendRequest,
  type EmailRecipient,
} from '@/services/emailSend';
import { getActiveEmailConfigs, type EmailConfigItem } from '@/services/emailConfig';
import { getActiveTemplates, type EmailTemplateItem } from '@/services/emailTemplate';
import { getDataSources, type DataSourceItem } from '@/services/dataSource';
import { request } from '@umijs/max';

const { TabPane } = Tabs;

interface Variable {
  name: string;
  display_name: string;
  field_type: string;
  is_email: boolean;
  is_name: boolean;
  sample_value?: string;
}

interface Recipient {
  email: string;
  name?: string;
  variables?: Record<string, any>;
}

interface EmailRecipientInput {
  email: string;
  name?: string;
  source?: string;
}

const EmailSendPage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [previewLoading, setPreviewLoading] = useState(false);
  
  // 数据状态
  const [emailConfigs, setEmailConfigs] = useState<EmailConfigItem[]>([]);
  const [templates, setTemplates] = useState<EmailTemplateItem[]>([]);
  const [dataSources, setDataSources] = useState<DataSourceItem[]>([]);
  const [recipients, setRecipients] = useState<Recipient[]>([]);

  // 收件人输入状态
  const [toRecipients, setToRecipients] = useState<EmailRecipientInput[]>([]);
  const [ccRecipients, setCcRecipients] = useState<EmailRecipientInput[]>([]);
  const [bccRecipients, setBccRecipients] = useState<EmailRecipientInput[]>([]);

  // 界面状态
  const [useTemplate, setUseTemplate] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<EmailTemplateItem | null>(null);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewData, setPreviewData] = useState<any>(null);
  const [recipientSelectorVisible, setRecipientSelectorVisible] = useState(false);
  const [tableDataInsertionVisible, setTableDataInsertionVisible] = useState(false);
  const [emailContent, setEmailContent] = useState({ subject: '', content: '' });
  const [sendMode, setSendMode] = useState<'batch' | 'personalized'>('batch');
  const [attachments, setAttachments] = useState<any[]>([]);



  // 获取基础数据
  useEffect(() => {
    fetchEmailConfigs();
    fetchTemplates();
    fetchDataSources();
    // 不初始化空白收件人，让用户主动添加
  }, []);

  const fetchEmailConfigs = async () => {
    try {
      const data = await getActiveEmailConfigs();
      setEmailConfigs(data);
    } catch (error: any) {
      message.error(error.message || '获取邮件配置失败');
    }
  };

  const fetchTemplates = async () => {
    try {
      const data = await getActiveTemplates();
      setTemplates(data);
    } catch (error: any) {
      message.error(error.message || '获取邮件模板失败');
    }
  };

  const fetchDataSources = async () => {
    try {
      const result = await getDataSources({ page: 1, size: 100 });
      // getDataSources返回的是分页数据，需要取items字段
      const data = result?.items || [];
      setDataSources(Array.isArray(data) ? data : []);
    } catch (error: any) {
      console.error('获取数据源失败:', error);
      // 设置为空数组，避免map错误
      setDataSources([]);
      message.error(error.message || '获取数据源失败');
    }
  };



  // 处理模板选择
  const handleTemplateChange = async (templateId: number) => {
    const template = templates.find(t => t.id === templateId);
    if (template) {
      setSelectedTemplate(template);
      setEmailContent({
        subject: template.subject,
        content: template.content,
      });
      form.setFieldsValue({
        subject: template.subject,
        content: template.content,
      });
    }
  };



  // 处理收件人选择确认
  const handleRecipientConfirm = (selectedRecipients: Recipient[], selectedVariables: Variable[]) => {
    // 将选择的收件人添加到收件人输入框
    const newToRecipients = selectedRecipients.map(r => ({
      email: r.email,
      name: r.name,
    }));
    setToRecipients(prev => [...prev, ...newToRecipients]);
    // 不要覆盖邮件内容的变量，收件人选择的变量是独立的
    setRecipientSelectorVisible(false);
    message.success(`已添加 ${selectedRecipients.length} 个收件人到收件人列表`);
  };

  // 处理表格数据插入确认
  const handleTableDataInsertionConfirm = (insertionData: any) => {
    if (insertionData.type === 'static') {
      // 静态数据插入：生成表格HTML
      const { fields, data } = insertionData;

      // 生成表格HTML
      let tableHtml = '<table border="1" style="border-collapse: collapse; width: 100%;">\n';

      // 表头
      tableHtml += '  <thead>\n    <tr>\n';
      fields.forEach((field: string) => {
        tableHtml += `      <th style="padding: 8px; background-color: #f5f5f5;">${field}</th>\n`;
      });
      tableHtml += '    </tr>\n  </thead>\n';

      // 表体
      tableHtml += '  <tbody>\n';
      data.forEach((row: any) => {
        tableHtml += '    <tr>\n';
        fields.forEach((field: string) => {
          tableHtml += `      <td style="padding: 8px;">${row[field] || ''}</td>\n`;
        });
        tableHtml += '    </tr>\n';
      });
      tableHtml += '  </tbody>\n</table>';

      // 插入到邮件内容
      const currentContent = form.getFieldValue('content') || '';
      const newContent = currentContent + '\n\n' + tableHtml;
      form.setFieldValue('content', newContent);
      setEmailContent(prev => ({ ...prev, content: newContent }));

      message.success(`已插入静态表格数据（${data.length} 行 × ${fields.length} 列）`);
    } else {
      // 动态数据插入：生成动态查询标记
      const { dataSource, table, fields, conditions } = insertionData;

      const dynamicQuery = {
        type: 'dynamic_table',
        dataSource: dataSource.id,
        table,
        fields,
        conditions
      };

      // 生成动态查询标记 - 使用更安全的JSON编码
      const jsonString = JSON.stringify(dynamicQuery);
      const queryTag = `{{DYNAMIC_TABLE:${jsonString}}}`;

      console.log('生成的动态查询标记:', queryTag);
      console.log('JSON字符串长度:', jsonString.length);

      // 插入到邮件内容
      const currentContent = form.getFieldValue('content') || '';
      const newContent = currentContent + '\n\n' + queryTag;
      form.setFieldValue('content', newContent);
      setEmailContent(prev => ({ ...prev, content: newContent }));

      message.success(`已插入动态表格查询（${fields.length} 个字段，${conditions.length} 个条件）`);
    }

    setTableDataInsertionVisible(false);
  };

  // 添加收件人
  const addRecipient = (type: 'to' | 'cc' | 'bcc') => {
    const newRecipient = { email: '', name: '' };
    if (type === 'to') {
      setToRecipients(prev => [...prev, newRecipient]);
    } else if (type === 'cc') {
      setCcRecipients(prev => [...prev, newRecipient]);
    } else {
      setBccRecipients(prev => [...prev, newRecipient]);
    }
  };

  // 删除收件人
  const removeRecipient = (type: 'to' | 'cc' | 'bcc', index: number) => {
    if (type === 'to') {
      setToRecipients(prev => prev.filter((_, i) => i !== index));
    } else if (type === 'cc') {
      setCcRecipients(prev => prev.filter((_, i) => i !== index));
    } else {
      setBccRecipients(prev => prev.filter((_, i) => i !== index));
    }
  };

  // 更新收件人
  const updateRecipient = (type: 'to' | 'cc' | 'bcc', index: number, field: 'email' | 'name', value: string) => {
    if (type === 'to') {
      setToRecipients(prev => prev.map((r, i) => i === index ? { ...r, [field]: value } : r));
    } else if (type === 'cc') {
      setCcRecipients(prev => prev.map((r, i) => i === index ? { ...r, [field]: value } : r));
    } else {
      setBccRecipients(prev => prev.map((r, i) => i === index ? { ...r, [field]: value } : r));
    }
  };



  // 预览邮件
  const handlePreview = async () => {
    try {
      const values = await form.validateFields(['subject', 'content']);
      setPreviewLoading(true);

      // 调用后端API进行完整预览
      const response = await request('/api/emails/preview', {
        method: 'POST',
        data: {
          subject: form.getFieldValue('subject') || '',
          content: form.getFieldValue('content') || '',
          // 传递一个示例收件人用于变量渲染
          to_recipients: [{ email: 'test@example.com', name: '测试用户' }],
          cc_recipients: [],
          bcc_recipients: [],
          template_variables: {}
        }
      });

      if (response.success) {
        setPreviewData(response.data);
        setPreviewVisible(true);
      } else {
        message.error(response.message || '预览失败');
      }
    } catch (error: any) {
      message.error('预览失败: ' + error.message);
    } finally {
      setPreviewLoading(false);
    }
  };

  // 渲染预览内容
  const renderPreviewContent = () => {
    if (previewData) {
      // 使用后端API返回的预览数据
      return (
        <div>
          <div style={{ marginBottom: 16 }}>
            <strong>主题：</strong>
            <div style={{ padding: '8px', backgroundColor: '#f5f5f5', borderRadius: '4px', marginTop: '4px' }}>
              {previewData.rendered_subject || '（无主题）'}
            </div>
          </div>
          <div>
            <strong>内容：</strong>
            <div
              style={{
                padding: '12px',
                backgroundColor: '#ffffff',
                border: '1px solid #d9d9d9',
                borderRadius: '4px',
                marginTop: '4px',
                minHeight: '200px',
                maxWidth: '100%',
                overflow: 'auto'
              }}
              dangerouslySetInnerHTML={{ __html: previewData.rendered_content || '（无内容）' }}
            />
          </div>
          {previewData.variables_used && previewData.variables_used.length > 0 && (
            <Alert
              message="变量预览"
              description="以上内容中的变量已替换为示例值，实际发送时将使用真实数据"
              type="info"
              style={{ marginTop: 16 }}
            />
          )}
        </div>
      );
    }

    // 如果没有预览数据，显示简单预览
    const subject = form.getFieldValue('subject') || '';
    const content = form.getFieldValue('content') || '';

    // 简单的变量替换预览（只处理系统变量）
    let previewSubject = subject;
    let previewContent = content;

    // 处理系统变量的示例值
    const now = new Date();
    const systemVariables = {
      'current_time': now.toLocaleString('zh-CN'),
      'current_date': now.toLocaleDateString('zh-CN'),
      'current_date_slash': `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, '0')}/${String(now.getDate()).padStart(2, '0')}`,
      'current_date_dash': `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`,
      'current_date_compact': `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`,
      'current_year_month': `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}`,
      'current_month': String(now.getMonth() + 1).padStart(2, '0'),
      'current_year': String(now.getFullYear()),
      'current_day': String(now.getDate()).padStart(2, '0'),
      'current_weekday': ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][now.getDay()],
    };

    // 替换系统变量
    Object.entries(systemVariables).forEach(([varName, varValue]) => {
      const variablePattern = new RegExp(`\\{\\{${varName}\\}\\}`, 'g');
      previewSubject = previewSubject.replace(variablePattern, varValue);
      previewContent = previewContent.replace(variablePattern, varValue);
    });

    return (
      <div>
        <div style={{ marginBottom: 16 }}>
          <strong>主题：</strong>
          <div style={{ padding: '8px', backgroundColor: '#f5f5f5', borderRadius: '4px', marginTop: '4px' }}>
            {previewSubject || '（无主题）'}
          </div>
        </div>
        <div>
          <strong>内容：</strong>
          <div
            style={{
              padding: '12px',
              backgroundColor: '#ffffff',
              border: '1px solid #d9d9d9',
              borderRadius: '4px',
              marginTop: '4px',
              minHeight: '200px',
              maxWidth: '100%',
              overflow: 'auto'
            }}
            dangerouslySetInnerHTML={{ __html: previewContent || '（无内容）' }}
          />
        </div>
        <Alert
          message="变量预览"
          description="以上内容中的系统变量已替换为示例值，实际发送时将使用真实数据"
          type="info"
          style={{ marginTop: 16 }}
        />
      </div>
    );
  };

  // 发送邮件
  const handleSend = async () => {
    try {
      const values = await form.validateFields();

      // 验证收件人
      if (toRecipients.length === 0) {
        message.warning('请至少添加一个收件人');
        return;
      }

      // 验证邮箱格式
      const allRecipients = [...toRecipients, ...ccRecipients, ...bccRecipients];
      const invalidEmails = allRecipients.filter(r => {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return !emailRegex.test(r.email);
      });

      if (invalidEmails.length > 0) {
        message.error(`发现无效的邮箱地址: ${invalidEmails.map(r => r.email).join(', ')}`);
        return;
      }

      setLoading(true);

      const sendRequest: EmailSendRequest = {
        email_config_id: values.email_config_id,
        subject: values.subject,
        content: values.content,
        recipients: allRecipients.map(r => ({
          email: r.email,
          name: r.name,
          variables: {},
        })),
        send_mode: sendMode,
        scheduled_time: values.scheduled_time,
        attachments: attachments, // 包含附件信息
      };

      await sendEmail(sendRequest);
      message.success(`邮件发送成功，共发送给 ${allRecipients.length} 个收件人`);

      // 清空表单
      form.resetFields();
      setToRecipients([]);
      setCcRecipients([]);
      setBccRecipients([]);
      setEmailContent({ subject: '', content: '' });
      setAttachments([]); // 清空附件

      // 可选：跳转到发送历史页面
      // history.push('/emails/tasks');
    } catch (error: any) {
      message.error(error.message || '邮件发送失败');
    } finally {
      setLoading(false);
    }
  };

  // 渲染智能收件人输入框
  const renderSmartRecipientInput = (
    type: 'to' | 'cc' | 'bcc',
    recipients: EmailRecipientInput[],
    label: string,
    placeholder: string
  ) => {
    const handleRecipientsChange = (newRecipients: EmailRecipientInput[]) => {
      if (type === 'to') {
        setToRecipients(newRecipients);
      } else if (type === 'cc') {
        setCcRecipients(newRecipients);
      } else {
        setBccRecipients(newRecipients);
      }
    };

    return (
      <Form.Item label={label}>
        <SmartRecipientInput
          value={recipients}
          onChange={handleRecipientsChange}
          placeholder={placeholder}
          maxCount={type === 'to' ? undefined : 50} // 收件人不限制，抄送和密送限制50个
        />
      </Form.Item>
    );
  };

  return (
    <PageContainer
      title="发送邮件"
      subTitle="编写和发送邮件"
    >
      <Row gutter={[16, 16]}>
        {/* 左侧：邮件编写 */}
        <Col xs={24} lg={16}>
          <Card title="邮件内容" size="small">
            <Form
              form={form}
              layout="vertical"
              onValuesChange={(changedValues) => {
                if (changedValues.subject !== undefined) {
                  setEmailContent(prev => ({ ...prev, subject: changedValues.subject }));
                }
                if (changedValues.content !== undefined) {
                  setEmailContent(prev => ({ ...prev, content: changedValues.content }));
                }
              }}
            >
              <Form.Item
                label="邮件配置"
                name="email_config_id"
                rules={[{ required: true, message: '请选择邮件配置' }]}
              >
                <Select placeholder="请选择邮件配置">
                  {emailConfigs.map(config => (
                    <Select.Option key={config.id} value={config.id}>
                      <Space>
                        <MailOutlined />
                        {config.name} ({config.smtp_host})
                      </Space>
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>



              <Form.Item label="使用模板">
                <Space>
                  <Switch
                    checked={useTemplate}
                    onChange={setUseTemplate}
                    checkedChildren="使用模板"
                    unCheckedChildren="自定义内容"
                  />
                  {useTemplate && (
                    <Select
                      placeholder="选择邮件模板"
                      style={{ width: 200 }}
                      onChange={handleTemplateChange}
                      allowClear
                    >
                      {templates.map(template => (
                        <Select.Option key={template.id} value={template.id}>
                          <Space>
                            <FileTextOutlined />
                            {template.name}
                          </Space>
                        </Select.Option>
                      ))}
                    </Select>
                  )}
                </Space>
              </Form.Item>

              {/* 智能收件人输入框 */}
              {renderSmartRecipientInput('to', toRecipients, '收件人', '输入收件人姓名或邮箱，回车添加')}
              {renderSmartRecipientInput('cc', ccRecipients, '抄送人', '输入抄送人姓名或邮箱，回车添加')}
              {renderSmartRecipientInput('bcc', bccRecipients, '密送人', '输入密送人姓名或邮箱，回车添加')}



              {/* 邮件编辑器 */}
              <EmailEditor
                form={form}
                showSubject={true}
                subjectLabel="邮件主题"
                contentLabel="邮件内容"
                subjectPlaceholder="请输入邮件主题，支持变量如：{{current_date}}"
                contentPlaceholder="请输入邮件内容，支持HTML和变量，如：今天是{{current_date}}，祝您工作愉快！"
                contentRows={10}
              />

              <Form.Item>
                <Space>
                  <Button
                    type="primary"
                    icon={<SendOutlined />}
                    onClick={handleSend}
                    loading={loading}
                  >
                    发送邮件
                  </Button>
                  <Button
                    icon={<EyeOutlined />}
                    onClick={handlePreview}
                    loading={previewLoading}
                  >
                    预览邮件
                  </Button>
                </Space>
              </Form.Item>

            </Form>
          </Card>
        </Col>

        {/* 右侧：系统变量面板和辅助功能 */}
        <Col xs={24} lg={8}>
          <Space direction="vertical" style={{ width: '100%' }} size="middle">
            {/* 系统变量面板 */}
            <SystemVariablePanel
              onVariableClick={(variableName) => {
                insertVariableAtCursor(form, variableName);
              }}
              title="系统变量"
            />

            {/* 附件管理 */}
            <AttachmentManager
              value={attachments}
              onChange={setAttachments}
              maxCount={5}
              maxSize={10}
              title="邮件附件"
            />

            {/* 表格数据插入 */}
            <Card title="表格数据插入" size="small">
              <Space direction="vertical" style={{ width: '100%' }}>
                <Button
                  type="primary"
                  icon={<TableOutlined />}
                  onClick={() => setTableDataInsertionVisible(true)}
                  block
                >
                  插入表格数据
                </Button>
                <div style={{ fontSize: '12px', color: '#666' }}>
                  支持静态表格和动态表格插入
                </div>
              </Space>
            </Card>

            {/* 收件人管理 */}
            <Card title="收件人管理" size="small">
              <Space direction="vertical" style={{ width: '100%' }}>
                <Button
                  type="primary"
                  icon={<DatabaseOutlined />}
                  onClick={() => setRecipientSelectorVisible(true)}
                  block
                >
                  从数据源批量添加收件人
                </Button>

                <Divider style={{ margin: '8px 0' }} />

                <Row gutter={16}>
                  <Col span={8}>
                    <Statistic
                      title="收件人"
                      value={toRecipients.length}
                      suffix="人"
                      valueStyle={{ color: toRecipients.length > 0 ? '#3f8600' : '#999' }}
                    />
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="抄送人"
                      value={ccRecipients.length}
                      suffix="人"
                      valueStyle={{ color: ccRecipients.length > 0 ? '#1890ff' : '#999' }}
                    />
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="密送人"
                      value={bccRecipients.length}
                      suffix="人"
                      valueStyle={{ color: bccRecipients.length > 0 ? '#722ed1' : '#999' }}
                    />
                  </Col>
                </Row>

                {/* 总计统计 */}
                {(toRecipients.length + ccRecipients.length + bccRecipients.length) > 0 && (
                  <Alert
                    message={`总计 ${toRecipients.length + ccRecipients.length + bccRecipients.length} 个收件人`}
                    type="success"
                    size="small"
                    style={{ marginTop: 8 }}
                  />
                )}
              </Space>
            </Card>
          </Space>
        </Col>
      </Row>

      {/* 收件人选择器 */}
      <IntegratedRecipientSelector
        visible={recipientSelectorVisible}
        onCancel={() => setRecipientSelectorVisible(false)}
        onConfirm={handleRecipientConfirm}
        dataSources={dataSources}
      />

      {/* 邮件预览对话框 */}
      <Modal
        title="邮件预览"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={[
          <Button key="close" onClick={() => setPreviewVisible(false)}>
            关闭
          </Button>,
        ]}
        width={800}
      >
        <div className="email-preview-content">
          {renderPreviewContent()}
        </div>
        <style jsx>{`
          .email-preview-content :global(img) {
            max-width: 100% !important;
            height: auto !important;
            display: block;
            margin: 10px 0;
          }
          .email-preview-content :global(p) {
            margin: 8px 0;
            line-height: 1.6;
          }
        `}</style>
      </Modal>

      {/* 表格数据插入对话框 */}
      <TableDataInsertion
        visible={tableDataInsertionVisible}
        onCancel={() => setTableDataInsertionVisible(false)}
        onConfirm={handleTableDataInsertionConfirm}
        dataSources={dataSources}
      />
    </PageContainer>
  );
};

export default EmailSendPage;
